package com.lvmou.index12306.framework.starter.bases;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;

/**
 * 单例对象容器
 */

// 设置无参构造方法为私有
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class Singleton {

    // 多线程hashMap
    private final static ConcurrentHashMap<String, Object> SINGLE_OBJECT_POOL= new ConcurrentHashMap<>();

    /**
     * 根据key获取单例对象
     */
    public static <T> T get(String key){
        Object result = SINGLE_OBJECT_POOL.get(key);
        return  result == null ? null : (T) result;
    }

    /**
     * 根据key获取单例对象
     * 为空时 通过supplier 构建单例对象并放入容器
     */
    public static <T> T get(String key, Supplier<T> supplier){
        Object result = SINGLE_OBJECT_POOL.get(key);
        if (result == null && (result = supplier.get()) != null){
            SINGLE_OBJECT_POOL.put(key, result);
        }
        return result != null ? (T) result : null;
    }

    /**
     * 对象放入容器
     */
    public static void put(Object value) {
        put(value.getClass().getName(), value);
    }

    /**
     * 获取容器的对象
     */
    public static void put(String key, Object value){
        SINGLE_OBJECT_POOL.put(key, value);
    }
}
